﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class passwordProtection : System.Web.UI.Page
{
    string[] questions = new string[]
    {
        "",
        "您父亲的生日是哪天？",
        "您母亲的生日是哪天？",
        "您祖父的姓名是什么？",
        "您小学同桌的姓名是什么？",
        "您初三班主任的姓名是什么？",
        "您高中是喜欢过的男生/女生叫什么名字？",
        "您的银行卡密码的前三位的任一组合？",
        "您曾经用过的学号/工号",
        "您出生所在医院/产院的名字",
        "您手机号中间3位的任一组合",
        "常用银行卡号后3位的任一组合"
    };
    protected void Page_Load(object sender, EventArgs e)
    {
        //最先验证用户是否登录
        if (Request.Cookies["userID"] == null)
        {
            Response.Redirect("notLogin.html", true);
            return;
        }
        else if (Request.Cookies["passwordProtectionStatus"] == null)
        {
            //密保已经完善
            Response.Redirect("alreadyProtected.html", true);
            return;
        }
        else if (Request.Cookies["passwordProtectionStatus"].Value == "2")
        {
            //已经提交问题，但是没有验证邮箱，跳转到验证邮箱的页面reEmail.aspx
            Response.Redirect("reEmail.aspx",true);
            return;
        }
        //检查完毕，适用本页面
    }
    protected void sendEmail_Click(object sender, EventArgs e)
    {
        //验证输入数据的有效性
        Regex emailAddressChecker = new Regex(@"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$", RegexOptions.IgnoreCase);

        if (question1_select.SelectedIndex == 0)
        {
            notification.InnerHtml = "您没有设置问题 1 FROM SERVER";
            return;
        }
        else if (question1_select.SelectedIndex == 12 && question1_custom_text.Text.Trim() == string.Empty)
        {
            notification.InnerHtml = "您没有设置自定义问题 1 FROM SERVER";
            return;
        }
        else if (answer1_text.Text.Trim() == string.Empty)
        {
            notification.InnerHtml = "您没有设置问题 1 的答案 FROM SERVER";
            return;
        }
        else if (question2_select.SelectedIndex == 0)
        {
            notification.InnerHtml = "您没有设置问题 2 FROM SERVER";
            return;
        }
        else if (question2_select.SelectedIndex == 12 && question2_custom_text.Text.Trim() == string.Empty)
        {
            notification.InnerHtml = "您没有设置自定义问题 2 FROM SERVER";
            return;
        }
        else if (answer2_text.Text.Trim() == string.Empty)
        {
            notification.InnerHtml = "您没有设置问题 2 的答案 FROM SERVER";
            return;
        }
        else if (email_text.Text.Trim() == string.Empty)
        {
            notification.InnerHtml = "您没有填写安全邮箱 FROM SERVER";
            return;
        }
        else if (!emailAddressChecker.IsMatch(email_text.Text.Trim()))
        {
            notification.InnerHtml = "您输入的邮箱地址不合法 FROM SERVER";
            return;
        }
        else
        {
            //一切检查完毕，向数据库写入数据
            //将问题和答案等存入数据库PasswordProtection表
            ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["connectionString"];
            using (SqlConnection dataBaseConnection = new SqlConnection(settings.ConnectionString))
            {
                dataBaseConnection.Open();

                string userID = Request.Cookies["userID"].Value;

                string queryString = "INSERT INTO PasswordProtection(userID, Question1, Answer1, Question2, Answer2) " +
                                     "VALUES(@userID, @Question1, @Answer1, @Question2, @Answer2)";
                SqlCommand command = new SqlCommand(queryString, dataBaseConnection);
                SqlParameter userIDParameter = new SqlParameter("@userID", userID);
                SqlParameter Question1Parameter = new SqlParameter("@Question1", (question1_select.SelectedIndex == 12 ? question1_custom_text.Text.Trim() : questions[question1_select.SelectedIndex]));
                SqlParameter Answer1Parameter = new SqlParameter("@Answer1", SHA1.Create().ComputeHash(Encoding.Unicode.GetBytes(answer1_text.Text.Trim())));
                SqlParameter Question2Parameter = new SqlParameter("@Question2", (question2_select.SelectedIndex == 12 ? question2_custom_text.Text.Trim() : questions[question2_select.SelectedIndex]));
                SqlParameter Answer2Parameter = new SqlParameter("@Answer2", SHA1.Create().ComputeHash(Encoding.Unicode.GetBytes(answer2_text.Text.Trim())));
                command.Parameters.AddRange(new SqlParameter[]
                {
                    userIDParameter,
                    Question1Parameter,
                    Answer1Parameter,
                    Question2Parameter,
                    Answer2Parameter
                });
                try
                {
                    command.ExecuteNonQuery();
                }
                catch (Exception exception)
                {
                    notification.InnerHtml = "数据库方面发生了错误，请联系我们以解决 AFTER INSERT INTO PasswordProtection " + exception.Message;
                    return;
                }

                //将邮箱地址存入数据库表users
                queryString = "UPDATE users " +
                              "SET email = @email " +
                              "WHERE userID = @userID";
                command.CommandText = queryString;
                command.Parameters.Clear();
                SqlParameter emailParameter = new SqlParameter("@email", email_text.Text.Trim());
                command.Parameters.AddRange(new SqlParameter[]
                {
                    userIDParameter,
                    emailParameter
                });
                try
                {
                    command.ExecuteNonQuery();
                }
                catch (Exception exception)
                {
                    notification.InnerHtml = "数据库方面发生了错误，请联系我们以解决 AFTER UPDATE users " + exception.Message;
                    return;
                }

                //发送验证邮件
                try
                {
                    Tools.SendVerifyEmail(email_text.Text.Trim(), userID, Request.Cookies["username"].Value);
                }
                catch (Exception exception)
                {
                    notification.InnerHtml = "邮件发送失败 " + exception.Message;
                    return;
                }

                //邮件发送成功后将Cookie中passwordProtectionStatus的值改为2
                Response.Cookies["passwordProtectionStatus"].Value = "2";

                //重定向到emailSent.html
                Response.Redirect("emailSent.aspx?emailAddress=" + email_text.Text.Trim());
            }
        }
    }
}